package com.huaishushu.controller;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huaishushu.common.R;
import com.huaishushu.dto.OrdersDto;
import com.huaishushu.entity.Orders;
import com.huaishushu.service.IOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author ChiBaoBaoHuaiShuShu
 * @since 2023-05-28
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    private IOrdersService ordersService;

    /**
     * 用户下单
     * 操作两张表，一个订单表orders，一张订单详情表order_detail
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("添加订单：{}",orders);
        ordersService.submit(orders);

        return R.success("用户下单成功");
    }

    /**
     * 后台订单的分页查询
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime 开始时间（下单）
     * @param endTime   终止时间（下单）
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize,String number, String beginTime, String endTime) {
        log.info("订单查询：开始时间和结束时间：{}·······{}", beginTime, endTime);

        Page<Orders> ordersPage = ordersService.page(page, pageSize, number, beginTime, endTime);

        return R.success(ordersPage);
    }

    /**
     * 修改订单状态
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Orders orders) {
        //log.info("修改订单状态：{}", orders);

        LambdaUpdateWrapper<Orders> luw = new LambdaUpdateWrapper<>();
        luw.set(Orders::getStatus, orders.getStatus());
        luw.eq(Orders::getNumber, orders.getId());
        boolean flag = ordersService.update(luw);
        if (flag) {
            return R.success("修改成功");
        }

        return R.error("修改订单状态失败！！！");
    }

    /**
     * 查询当前用户的订单，并进行分页
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(Integer page, Integer pageSize) {
        Page<OrdersDto> ordersDtoPage = ordersService.userPage(page, pageSize);
        log.info("移动端拥有查看订单的分页信息，{}",ordersDtoPage.getRecords());
        return R.success(ordersDtoPage);
    }

    /**
     * 再来一单
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders) {
        log.info("再来一单的订单id：{}",orders.getId());
        ordersService.again(orders);

        return R.success("再来一单成功");
    }


}
